package top.xiaoshuaila.moments.service;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.xiaoshuaila.moments.mapper.MessageMapper;
import top.xiaoshuaila.moments.mapper.ZanMapper;
import top.xiaoshuaila.moments.pojo.Users;
import top.xiaoshuaila.moments.utils.Dateutils;
import top.xiaoshuaila.moments.utils.Usersutils;

import java.util.Objects;

@Service
public class ZanServiceImpl implements ZanService {
    @Autowired
    private ZanMapper zanMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean dianzan(long dyid,long userid,String dyname) {
        Users users= Usersutils.getuser();
        long manid=users.getId();
        String username=users.getRealname();
        boolean iszan=zanMapper.iszan(dyid,manid);
        messageMapper.deleteMessageszan(dyid,manid);
        if(iszan)
        {
            zanMapper.removezan(dyid,manid);
        }
        else {
            zanMapper.addzan(dyid,manid, Dateutils.getDatetime());
            if(userid!=manid)
            messageMapper.addMessageszan(0,dyid,userid,"用户“"+username+"“点赞了您的动态”"+dyname+"“",Dateutils.getDatetime(),manid);
        }
        if(redisTemplate.opsForValue().get("id-" + userid)!=null)
            redisTemplate.delete((redisTemplate.opsForValue().get("id-" + userid)));
        redisTemplate.delete("id-"+manid);
        return !iszan;
    }

    @Override
    public boolean zhuanfa(String dyid) {
        Users users=Usersutils.getuser();
        zanMapper.adddy(users.getId(),Dateutils.getDatetime(),true,dyid,false);
        return true;
    }

    @Override
    public int gettotal(long dyid) {
        return zanMapper.gettotal(dyid);
    }
}
